package golang

import (
	"fmt"
	"golang.org/x/net/websocket"
	_ "golang.org/x/net/websocket"
	"net/http"
)

/**
golang官方提供的websocket server
*/
func GolangServer() {
	http.Handle("/push", websocket.Handler(Push))
	http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write([]byte("hello"))
		writer.WriteHeader(200)
	})

	server := http.FileServer(http.Dir("/Users/fanshuai/project-test/go/demo/web/websocket/static"))
	http.Handle("/static/", http.StripPrefix("/static/", server))

	http.ListenAndServe(":9000", nil)
}

func Push(conn *websocket.Conn) {
	var err error
	for {
		for i := 0; i < 5; i++ {
			websocket.Message.Send(conn, "hello a")
		}

		var reply string
		if err = websocket.Message.Receive(conn, &reply); err != nil {
			fmt.Println(err)
			break
		}

		fmt.Println("receive from client:" + reply)
	}
}
